<?php
/**
 * 分类管理程序
 */
class CatAction extends BaseAction{
	function _initialize() {
		parent::_initialize();
		$this->dao=M("ProductCategoryTag");
	}
	
	/**
	 * 分类列表
	 * @author tb
	 *@date 2014.1.9
	 *@time 下午4:57:17
	 */
	function index(){
		$cid = $_REQUEST['cid'];
		//刷选信息
		$where = array();		
		$where ['parent_id'] = $cid;
		$where = self::create_where($where); 
		$count=$this->dao->where($where)->count();
		$this->assign("totalCount",$count);
		if($count>0){
			$page=new Page($count,$this->listrows);
			$list=$this->dao->where($where)->order($this->order)->limit($page->firstRow.','.$page->listRows)->select();
			$this->assign('list',$list);
		}
		$this->assign('cid',$cid);
		$this->assign('catid',$cid);
		$this->display('index');	
	}
	
	/**
	 * 返回分类树
	 * copy by tb
	 *@date 2014.1.9
	 *@time 下午4:57:17
	 */
	function all() {
		//内容管理综合页面
		parent::_cache(1,'cats');
		$this->cats_tree();
		$this->display();
	}//end all
	
	
	
	/*
	 * 添加分类 （直接添加，添加下级分类）
	* @author tb
	* @date 2014.1.10
	* */
	function add(){
		$pid = isset($_REQUEST['cid']) ? $_REQUEST['cid'] : $_GET['pid'];
		if($pid){
			$info=$this->dao->where("id=".$pid)->find();
	        if($info){
	            $this->assign('pinfo',$info);
	            $this->display();
	        }
		}else{
			 $this->display();
		}
		
	}
	
	/*
	 * 保存分类信息（添加和修改）
	* update by tb 2014.1.9
	*
	* */
	function save(){
		$id = $_POST['id'];
		$data['parent_id']=intval($_POST['cat_id']);
		$data['name']=$_POST['name'];
		$data['type']='1';
		$path = $this->dao->field('path')->where(array('id'=>$data['parent_id']))->find();
		$path = explode(',', $path['path']);
		$path[] = $data['parent_id'];
		$data['path'] = implode(',', $path);
		if($id){
			//update
			$data['id'] = $id;
			$reid = $this->dao->save($data);
		}else{
			//add
			$reid = $this->dao->add($data);
		}
		if($reid===FALSE){
			$this->_ajm(300,'数据写入失败，请重试'.$this->dao->getlastsql(),0);
		}else{
			$this->_ajm(200,'数据保存成功',0);
		}
	}
	
	
	/**
	 * 返回分类树
	 * copy by tb
	 *@date 2014.1.9
	 *@time 下午4:57:17
	 */
	function cats_tree() {
		//返回分类树
		$cats=F("cats");
		$this->assign("cats",$cats);
		$cats=list_to_tree($cats,'id','parent_id');
		$tree=self::tree($cats);
		$this->assign("tree",$tree);
	}//end cats_tree
	
	
	/*
	 * 分类树的输出
	*copy by tb
	* @date 2014.1.9
	* */
	function tree($arr, $urls = 'Cat/index') {
		$str = '';
		foreach ( $arr as $key => $v ) {
			$pid = isset ( $_REQUEST ['pid'] ) ? intval ( $_REQUEST ['pid'] ) : 1;
			$ckd = ($pid == $v ['id']) ? 'myselect="selected"' : '';
			if ($v ['level'] < 10) {
				$str .= "<li " . $ckd . "><a href=\"" . U ( $urls, array (
						"cid" => $v ['id']
				) ) . "\" target=\"ajax\" rel=\"catBox\">" . $v ['name'] . '</a>';
				if ($v ['_child']) {
					$str .= "<ul>";
					$str .= self::tree ( $v ['_child'] );
					$str .= "</ul>";
				}
			} else {
				$str .= "<li><a href=\"javascript:void(0);\">" . $v ['name'] . '</a>';
			}
			$str .= "</li>";
		}
		return $str;
	}
	
	
	/*
	 * 查找带 刷选
	* @author tb
	* @date 2014.1.9
	* */
	function lookup(){
		$maps=array();
		//帅选下级分类  由于不能查找带回，代码先注释
// 		if($_POST['cat_name']){
// 			$maps['name'] = array('LIke','%'.$_POST['cat_name'].'%');
			
// 		}		
// 		if($_POST['cat_id']){
// 			$maps['parent_id'] = $_POST['cat_id'];
// 			$maps['_logic'] = 'or';
// 		}
// 		$this->assign('name',$_POST['cat_name']);

		if($_POST['name']){
			$maps['name'] = array('LIke','%'.$_POST['name'].'%');
		}
		
		$this->assign('name',$_POST['name']);
		parent::lookup($maps);
		
	}
	

	
	
	
	
	/**
	 * 添加分类的前置步骤
	 * 查询现有的分类，并以树状显示
	 */
	function _before_add(){
		$cats = F('cats');
		$this->assign("cats",$cats);
		$pid = isset($_REQUEST['pid'])?intval($_REQUEST['pid']):1;
		$this->assign('pcats',$cats[$pid]);
		$this->assign('pid',$pid);
	}
	
	function _before_edit(){
		$cats = F('cats');
		$this->assign("cats",$cats);
		$pid = isset($_REQUEST['pid'])?intval($_REQUEST['pid']):1;
		$this->assign('pcats',$cats[$pid]);
		$id = isset($_REQUEST['id'])?intval($_REQUEST['id']):0;
		$this->assign('info',$cats[$id]);
		$this->assign('pid',$pid);
		$this->assign('id',$id);
	}
	

	
	
	function tree_sel(){
		$cats=F("cats");
		$cats=list_to_tree($cats,'id','parent_id');
		$cats=baktree($cats);
		$this->assign("tree",$cats);
		$this->display();
	}
	
	function delall(){
		$dao=$this->dao;
        $pk=$dao->getPk();
        $id=intval($_REQUEST['id']);
        $ids=$_REQUEST['ids'];
        $where=array();
        if(empty($id)){
        	if(in_array('196',$ids)){
        		$this->_ajm(300,'操作错误，回收站不能删除');
        	}
            $ids=implode(',',$ids);
            $where[$pk]=array('IN',$ids);
        }else{
        	if($id=='196'){
        		$this->_ajm(300,'操作错误，回收站不能删除');
        	}
            $where[$pk]=array('eq',$id);
        }
        $res=$dao->where($where)->delete();
        if($res===FALSE){
            $this->_ajm(300,'操作错误，请重试');
        }else{
            $this->_ajm(200,'操作成功',1,U(MODULE_NAME.'/all'));
        }
	}
	
	/**
	*删除分类树
	*@date 2014-2-25
	*@time 下午4:21:25
	*/
	function del_tree() {
	//删除分类树
		$id=intval($_REQUEST['ids']['0']);
		if(empty($id)){
			$this->_ajm(300,'操作错误，请选择一条记录');
		}
		if($id=='196'){
			$this->_ajm(300,'操作错误，回收站不能删除');
		}
		$where='id='.$id.' OR FIND_IN_SET('.$id.',`path`)>0';
		$res=$this->dao->where($where)->delete();
		if($res===FALSE){
			$this->_ajm(300,'操作错误，请重试');
		}else{
			$this->_ajm(200,'操作成功',1,U(MODULE_NAME.'/all'));
		}
	}//end del_tree

	/**
	*修正分类的path
	*@date 2013-9-12
	*@time 下午12:22:43
	*/
	function path() {
	//修正分类的path
		$dao=M("ProductCategoryTag");
		$dao->where('id=1')->save(array('parent_id'=>'0','path'=>'0'));
		$dao->where('parent_id=0 AND id>1')->save(array('parent_id'=>'1','path'=>'0,1'));
		$dao->where('parent_id=1')->save(array('parent_id'=>'1','path'=>'0,1'));
		$data=$dao->where('parent_id=1')->select();
		do {
			$new=$tmp=array();
			foreach ($data as $v){
				$dao->where('parent_id='.$v['id'])->save(array('path'=>$v['path'].','.$v['id']));
				$tmp=$dao->where('parent_id='.$v['id'])->select();
				foreach ($tmp as $sv){
					$new[]=$sv;
				}
			}
			$data=$new;
			$new=array();
		}while (!empty($data));
		exit ("修正成功");
	}//end path
	
	/**
	*修正分类的级别
	*@date 2013-9-17
	*@time 下午2:02:04
	*/
	function level() {
	//修正分类的级别
		$dao=M("ProductCategoryTag");
		$data=$dao->field("id,level,path")->order('id ASC')->select();
		foreach ($data as $v){
			$path=explode(',', $v['path']);
			$level=count($path);
			$dao->where("id=".$v['id'])->save(array('level'=>$level));
		}
		exit ("修正成功");
	}//end level



/**
 * 树形菜单生成函数查找带找回的
 * @param array $arr 需要树形化的数组
 * @return string $str
 */
function baktree($arr,$flag=false){
	$str='';
	foreach ($arr as $key => $v) {
		$str.="<li><a href=\"javascript:\" onclick=\"\$.bringBack({id:'{$v['id']}', name:'{$v['name']}'})\">".$v['name'].'</a> | ';
		if($v['_child']){
			$str.="<ul>";
			$str.=baktree($v['_child']);
			$str.="</ul>";
		}
		$str.="</li>";
	}
	return $str;
}


function _before_update(){
	$_POST['parent_id']=intval($_POST['pcat_id']);
}
function _after_insert(){
	$this->_cache(1,'cats');
}

function _after_update(){
	$this->_cache(1,'cats');
}

		
}